package plan

import (
	"fmt"
	"mini-sql/expression"
	"mini-sql/model"
	"mini-sql/storage"
)

type DeletePlanNode struct {
	source          PlanNode
	deleteStatement *model.DeleteStatement
	storePool       *storage.StorePool
	tableStore      storage.StoreInterface
}

func NewDeletePlanNode(source PlanNode, deleteStatement *model.DeleteStatement, storePool *storage.StorePool) PlanNode {
	return &DeletePlanNode{
		source:          source,
		deleteStatement: deleteStatement,
		storePool:       storePool,
	}
}

func (node *DeletePlanNode) Prepare() error {
	tableName, err := expression.GetTableName(node.deleteStatement.TableRef)
	if err != nil {
		return err
	}
	if tableName == "" {
		return fmt.Errorf("SelectPlan: tableName is empty")
	}
	tableStore, err := node.storePool.GetTableStore(tableName)
	if err != nil {
		return err
	}
	node.tableStore = tableStore

	return node.source.Prepare()
}

func (node *DeletePlanNode) GetNextTuple() (*model.TableTuple, error) {
	tuple, err := node.source.GetNextTuple()
	if err != nil {
		return nil, err
	}
	if tuple == nil {
		return nil, nil
	}
	// 执行删除
	err = node.tableStore.DeleteRow(*tuple)
	if err != nil {
		return nil, err
	}
	return tuple, nil
}
